package com.score;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.traaax.music.Mp3Jni;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class StartActivity extends Activity {
    public static int mDiff = 2;
    private boolean isPlayType = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_startactivity);
        Mp3Jni.check(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, android.Manifest.permission.RECORD_AUDIO)) {
                String[] perms = new String[]{android.Manifest.permission.RECORD_AUDIO};
                ActivityCompat.requestPermissions(this, perms, 10);
                return;
            }
        }
        ((RadioGroup) findViewById(R.id.rg)).setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rg1) {

                    isPlayType = true;


                    mDiff = 1;
                } else if (checkedId == R.id.rg2) {
                    isPlayType = false;
                    mDiff = 2;
                } else {
                    mDiff = 4;
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == 10) {
            if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "请给与录音权限", Toast.LENGTH_LONG).show();
            }
        }
    }
    private int offset = 0; // 当前音频数据的偏移量
    public void go(View v) throws IOException {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, android.Manifest.permission.RECORD_AUDIO)) {
                String[] perms = new String[]{android.Manifest.permission.RECORD_AUDIO};
                ActivityCompat.requestPermissions(this, perms, 10);
                return;
            }
        }

//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    String banzuo = copyFile2();
//                    String yuanchang = copyFile();
//
////        byte[] banzuobytes = Mp3ToByteArray.convertMp3ToByteArray(new File(banzuo));
////        byte[] yuanchangbytes = Mp3ToByteArray.convertMp3ToByteArray(new File(yuanchang));
//
//                    Mp3Decoder mp3Decoder = new Mp3Decoder();
//                    String pcm = mp3Decoder.decodeMP3ToPCM(banzuo);
//                    String pcmyuanchang = mp3Decoder.decodeMP3ToPCM(yuanchang);
//                    int sampleRateInHz = 44100;
//                    int channelConfig = AudioFormat.CHANNEL_OUT_MONO;
//                    int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
//                    int bufferSizeInBytes = AudioTrack.getMinBufferSize(sampleRateInHz, channelConfig, audioFormat);
//
//                    AudioTrack audioTrack = new AudioTrack(
//                            AudioManager.STREAM_MUSIC,
//                            sampleRateInHz,
//                            channelConfig,
//                            audioFormat,
//                            bufferSizeInBytes,
//                            AudioTrack.MODE_STREAM
//                    );
//
//
//                    File file = new File(pcm);
//                    File file2 = new File(pcmyuanchang);
//
//                    byte[] audioData1 = Mp3ToByteArray.convertMp3ToByteArray(file);
//                    byte[] audioData2 = Mp3ToByteArray.convertMp3ToByteArray(file2);
//
////                    byte[] buffer = new byte[bufferSizeInBytes];
////                    FileInputStream fis = new FileInputStream(file);
////                    FileInputStream fis2 = new FileInputStream(file2);
//                    audioTrack.play();
//                    while (true) { // 假设isPlaying是一个标志位，用于控制循环是否继续
//                        // 根据当前索引选择音频数据
//                        byte[] audioData = isPlayType ? audioData1 : audioData2;
//                        // 计算需要写入的音频数据量（基于AudioTrack的缓冲区大小和当前偏移量）
//                        int writeSize = Math.min(audioData.length - offset, bufferSizeInBytes);
//
//                        // 写入音频数据到AudioTrack
//                        audioTrack.write(audioData, offset, writeSize);
//                        // 更新偏移量
//                        offset += writeSize;
//
//                        // 如果到达音频数据的末尾，则重置偏移量并可能切换音频
//                        if (offset >= audioData.length) {
//                            offset = 0; // 重置偏移量以循环播放
//                        }
//                    }
//                } catch (IOException e) {
//                    throw new RuntimeException(e);
//                }
//            }
//        }).start();


        Intent i = new Intent(this, ScoreMainActivity.class);
        startActivity(i);
    }

    private String copyFile2() {
        String imageDir = DirManager.getImageDir();
        File file = new File(imageDir + "/伴奏.mp3");
        try {
            InputStream is = getAssets().open("十年/伴奏.mp3");
            FileOutputStream fos = new FileOutputStream(file);
            byte[] buffer = new byte[4096];
            int len = -1;
            while ((len = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            fos.flush();
            fos.close();
            is.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return file.getAbsolutePath();
    }

    private String copyFile() {
        String imageDir = DirManager.getImageDir();
        File file = new File(imageDir + "/原唱.mp3");
        try {
            InputStream is = getAssets().open("十年/原唱.mp3");
            FileOutputStream fos = new FileOutputStream(file);
            byte[] buffer = new byte[4096];
            int len = -1;
            while ((len = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            fos.flush();
            fos.close();
            is.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return file.getAbsolutePath();
    }
}
